package demo1;

public class Test {
        public boolean hasCycle(ListNode head) {
            if(head==null)return false;
            ListNode slow=head;
            ListNode fast=head;
            while(fast.next!=null&&fast.next.next!=null){
                slow=slow.next;
                fast=fast.next.next;
                if(slow==fast)return true;
            }
            return false;
        }

        public static void main(String[] args) {
            Test test = new Test();

            // 测试用例1: 带环链表
            ListNode head1 = new ListNode(3);
            ListNode node2 = new ListNode(2);
            ListNode node3 = new ListNode(0);
            ListNode node4 = new ListNode(-4);

            head1.next = node2;
            node2.next = node3;
            node3.next = node4;
            node4.next = node2; // 形成环

            System.out.println("带环链表测试结果: " + test.hasCycle(head1)); // true

            // 测试用例2: 不带环链表
            ListNode head2 = new ListNode(1);
            head2.next = new ListNode(2);
            head2.next.next = new ListNode(3);

            System.out.println("不带环链表测试结果: " + test.hasCycle(head2)); // false

            // 测试用例3: 空链表
            System.out.println("空链表测试结果: " + test.hasCycle(null)); // false

            // 测试用例4: 单节点自环
            ListNode singleNode = new ListNode(1);
            singleNode.next = singleNode;
            System.out.println("单节点自环链表测试结果: " + test.hasCycle(singleNode)); // true
        }

    }
